using Microsoft.AspNetCore.Mvc;
using GroupSix.Application.Services;
using GroupSix.Application.Dtos;
using GroupSix.Domain.Services;

namespace GroupSix.Api.Controllers;

[ApiController]
[Route("api/auth")]
public class AuthController : ControllerBase
{
    private readonly UserService _userService;
    private readonly ITokenService _tokenService;

    public AuthController(UserService userService, ITokenService tokenService)
    {
        _userService = userService;
        _tokenService = tokenService;
    }

    /// <summary>
    /// 用户注册
    /// </summary>
    /// <param name="request">注册请求</param>
    /// <returns>注册结果</returns>
    [HttpPost("register")]
    public async Task<IActionResult> Register([FromBody] UserRegisterRequestDto request)
    {
        try
        {
            // 验证模型状态
            if (!ModelState.IsValid)
            {
                var errors = ModelState.Values
                    .SelectMany(v => v.Errors)
                    .Select(e => e.ErrorMessage)
                    .ToList();
                
                return BadRequest(new { 
                    success = false, 
                    message = "输入验证失败", 
                    errors = errors 
                });
            }

            var response = await _userService.RegisterAsync(request);

            return Ok(new { 
                success = true, 
                data = response, 
                message = "注册成功" 
            });
        }
        catch (ArgumentException ex)
        {
            return BadRequest(new { 
                success = false, 
                message = ex.Message 
            });
        }
        catch (InvalidOperationException ex)
        {
            return BadRequest(new { 
                success = false, 
                message = ex.Message 
            });
        }
        catch (Exception ex)
        {
            return StatusCode(500, new { 
                success = false, 
                message = $"注册失败: {ex.Message}" 
            });
        }
    }

    /// <summary>
    /// 用户登录
    /// </summary>
    /// <param name="request">登录请求</param>
    /// <returns>登录结果</returns>
    [HttpPost("login")]
    public async Task<IActionResult> Login([FromBody] UserLoginRequestDto request)
    {
        try
        {
            var (user, token) = await _userService.LoginAsync(request.Username, request.Password, request.RememberMe);
            
            var response = new UserLoginResponseDto
            {
                UserId = user.Id,
                Username = user.Username,
                Nickname = user.Nickname,
                Email = user.Email,
                Token = token,
                Status = user.Status
            };

            return Ok(new { success = true, data = response, message = "登录成功" });
        }
        catch (Exception ex)
        {
            return BadRequest(new { success = false, message = ex.Message });
        }
    }

    /// <summary>
    /// 用户登出
    /// </summary>
    /// <param name="request">登出请求</param>
    /// <returns>登出结果</returns>
    [HttpPost("logout")]
    public async Task<IActionResult> Logout([FromBody] UserLogoutRequestDto request)
    {
        try
        {
            // 验证请求数据
            if (string.IsNullOrEmpty(request.Token))
            {
                return BadRequest(new { success = false, message = "Token不能为空" });
            }

            if (request.UserId == Guid.Empty)
            {
                return BadRequest(new { success = false, message = "用户ID不能为空" });
            }

            // 企业级登出逻辑：
            // 1. 验证Token有效性
            // 2. 将Token加入黑名单（防止继续使用）
            // 3. 记录登出日志
            // 4. 如果是强制登出所有设备，则清除该用户的所有token
            // 5. 返回登出确认

            // 验证Token有效性
            var isValidToken = await _tokenService.ValidateTokenAsync(request.Token);
            if (!isValidToken)
            {
                return BadRequest(new { success = false, message = "无效的Token" });
            }

            // 验证Token中的用户ID是否匹配
            var tokenUserId = _tokenService.GetUserIdFromToken(request.Token);
            if (tokenUserId != request.UserId)
            {
                return BadRequest(new { success = false, message = "Token与用户ID不匹配" });
            }

            // 将Token加入黑名单
            var blacklistResult = await _tokenService.BlacklistTokenAsync(request.Token, request.UserId, request.Reason ?? "用户主动登出");
            if (!blacklistResult)
            {
                return BadRequest(new { success = false, message = "Token黑名单操作失败" });
            }

            // 如果是强制登出所有设备
            if (request.ForceLogoutAllDevices)
            {
                await _tokenService.ForceLogoutAllDevicesAsync(request.UserId, request.Reason ?? "强制登出所有设备");
            }

            var response = new
            {
                success = true,
                message = "登出成功",
                data = new
                {
                    userId = request.UserId,
                    token = request.Token.Substring(0, Math.Min(20, request.Token.Length)) + "...", // 只显示部分Token
                    logoutTime = DateTime.UtcNow,
                    reason = request.Reason ?? "用户主动登出",
                    forceLogoutAllDevices = request.ForceLogoutAllDevices
                }
            };

            return Ok(response);
        }
        catch (Exception ex)
        {
            return BadRequest(new { success = false, message = $"登出失败: {ex.Message}" });
        }
    }

    /// <summary>
    /// 刷新Token
    /// </summary>
    /// <returns>新的Token</returns>
    [HttpPost("refresh")]
    public IActionResult RefreshToken()
    {
        // 这里可以添加刷新token的逻辑
        return Ok(new { success = true, message = "Token刷新成功" });
    }

    /// <summary>
    /// 发送验证码
    /// </summary>
    /// <param name="request">发送验证码请求</param>
    /// <returns>发送结果</returns>
    [HttpPost("send-verification-code")]
    public IActionResult SendVerificationCode([FromBody] SendVerificationCodeRequestDto request)
    {
        try
        {
            // 验证邮箱格式
            if (string.IsNullOrEmpty(request.Email))
            {
                return BadRequest(new { success = false, message = "邮箱不能为空" });
            }

            // 这里应该实现发送验证码的逻辑
            // 暂时返回模拟成功响应
            return Ok(new { success = true, message = "验证码已发送" });
        }
        catch (Exception ex)
        {
            return BadRequest(new { success = false, message = $"发送验证码失败: {ex.Message}" });
        }
    }

    /// <summary>
    /// 验证验证码
    /// </summary>
    /// <param name="request">验证验证码请求</param>
    /// <returns>验证结果</returns>
    [HttpPost("verify-code")]
    public IActionResult VerifyCode([FromBody] VerifyCodeRequestDto request)
    {
        try
        {
            if (string.IsNullOrEmpty(request.Email) || string.IsNullOrEmpty(request.Code))
            {
                return BadRequest(new { success = false, message = "邮箱和验证码不能为空" });
            }

            // 这里应该实现验证验证码的逻辑
            // 暂时返回模拟成功响应
            return Ok(new { success = true, message = "验证码验证成功" });
        }
        catch (Exception ex)
        {
            return BadRequest(new { success = false, message = $"验证码验证失败: {ex.Message}" });
        }
    }

    /// <summary>
    /// 重置密码
    /// </summary>
    /// <param name="request">重置密码请求</param>
    /// <returns>重置结果</returns>
    [HttpPost("reset-password")]
    public IActionResult ResetPassword([FromBody] ResetPasswordRequestDto request)
    {
        try
        {
            if (string.IsNullOrEmpty(request.Email) || string.IsNullOrEmpty(request.VerificationCode) || string.IsNullOrEmpty(request.NewPassword))
            {
                return BadRequest(new { success = false, message = "所有字段都不能为空" });
            }

            // 这里应该实现重置密码的逻辑
            // 暂时返回模拟成功响应
            return Ok(new { success = true, message = "密码重置成功" });
        }
        catch (Exception ex)
        {
            return BadRequest(new { success = false, message = $"密码重置失败: {ex.Message}" });
        }
    }
} 